<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class Score extends AdminBase
{
    protected $student_model;
    protected $classes_model;
    protected $exam_model;
    protected $score_model;
    protected $admin_user_model;

    public function __construct()
    {
        parent::__construct();
        $this->student_model    = new \app\common\model\Student();
        $this->classes_model    = new \app\common\model\Classes();
        $this->exam_model       = new \app\common\model\Exam();
        $this->score_model      = new \app\common\model\Score();
        $this->admin_user_model = new \app\common\model\AdminUser();
    }

    /**
     * 成绩列表
     * @param $exam_id
     * @param $class_id
     * @param $name
     * @param $page
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index($exam_id = 0, $class_id = 0, $name = '', $page = 1){
        $map = [];

        if ($exam_id > 0) {
            $map['exam_id'] = $exam_id;
        }

        if ($class_id > 0) {
            $map['class_id'] = $class_id;
        }

        if (!empty($name)) {
            $map['name'] = ['like', "%{$name}%"];
        }

        $exam_list  = $this->exam_model->all();
        $class_list = $this->classes_model->all();

        $score_list = $this->score_model->where($map)->order('id DESC')
            ->paginate(10, false, ['page' => $page])->each(function($item, $key){
                $exam_id = $item['exam_id'];
                $class = $this->exam_model->find($exam_id);
                $item['exam_name'] = $class['exam_name'];

                $class_id = $item['class_id'];
                $class = $this->classes_model->find($class_id);
                $item['class_name'] = $class['class_name'];

                $user_id = $item['user_id'];
                $user = $this->admin_user_model->find($user_id);
                $item['username'] = $user['username'];
            });

        return $this->fetch('index', [
            'exam_list'  => $exam_list,
            'class_list' => $class_list,
            'score_list' => $score_list,
            'name'       => $name,
            'class_id'   => $class_id,
            'exam_id'    => $exam_id,
        ]);
    }


    /**
     * Excel导出
     * @param $exam_id
     * @param $class_id
     * @param $name
     * @return void
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function excel($exam_id = 0, $class_id = 0, $name = '')
    {
        $map = [];

        if ($exam_id > 0) {
            $map['exam_id'] = $exam_id;
        }

        if ($class_id > 0) {
            $map['class_id'] = $class_id;
        }

        if (!empty($name)) {
            $map['name'] = ['like', "%{$name}%"];
        }

        $score_list = $this->score_model->where($map)->order('id DESC')
            ->paginate(10000)->each(function($item, $key){
                $exam_id = $item['exam_id'];
                $class = $this->exam_model->find($exam_id);
                $item['exam_name'] = $class['exam_name'];

                $class_id = $item['class_id'];
                $class = $this->classes_model->find($class_id);
                $item['class_name'] = $class['class_name'];

                $user_id = $item['user_id'];
                $user = $this->admin_user_model->find($user_id);
                $item['username'] = $user['username'];
            });

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 设置表头
        $headers = ['ID', '姓名', '分数', '考试', '班级', '备注'];
        $col = 'A';
        foreach ($headers as $index => $header) {
            $sheet->setCellValue($col . '1', $header);
            $col++;
        }

        // 填充数据
        $row = 2;
        foreach ($score_list as $student) {
            $sheet->setCellValue('A' . $row, $student['id']);
            $sheet->setCellValue('B' . $row, $student['name']);
            $sheet->setCellValue('C' . $row, $student['score']);
            $sheet->setCellValue('D' . $row, $student['exam_name']);
            $sheet->setCellValue('E' . $row, $student['class_name']);
            $sheet->setCellValue('F' . $row, $student['remark']);
            $row++;
        }

        // 输出
        $filename = '学生考试导出_' . date('YmdHis') . '.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        exit;
    }

    /**
     * 添加成绩
     * @return mixed|void
     * @throws \think\exception\DbException
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $result_validate = $this->validate($data, 'Score.add');
            if ($result_validate !== true) {
                $this->error($result_validate);
            }

            $student_by_name = $this->student_model->where(['name' => $data['name']])->find();
            if (!$student_by_name) {
                $this->error('姓名错误，数据库查无此人！');
            }

            $student_by_class_id = $this->student_model->where(['class_id' => $data['class_id'],'name'=>$data['name']])->find();
            if (!$student_by_class_id) {
                $this->error('姓名错误，选择班级内无此人!');
            }

            $result = $this->score_model->allowField(true)->save($data);
            if ($result) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        } else {
            $class_list = $this->classes_model->all();
            $exam_list = $this->exam_model->all();
            return $this->fetch('add', [
                'class_list' => $class_list,
                'exam_list'  => $exam_list,
            ]);
        }
    }

    /**
     * 编辑成绩
     * @param $id
     * @return mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id = 0){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $result_validate = $this->validate($data, 'Score.edit');
            if ($result_validate !== true) {
                $this->error($result_validate);
            }

            $student_by_name = $this->student_model->where(['name' => $data['name']])->find();
            if (!$student_by_name) {
                $this->error('姓名错误，数据库查无此人！');
            }

            $student_by_class_id = $this->student_model->where(['class_id' => $data['class_id'],'name'=>$data['name']])->find();
            if (!$student_by_class_id) {
                $this->error('姓名错误，选择班级内无此人!');
            }

            $result = $this->score_model->allowField(true)->save($data, $id);
            if ($result) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        } else {
            $class_list = $this->classes_model->all();
            $exam_list = $this->exam_model->all();
            $score = $this->score_model->find($id);
            return $this->fetch('edit', [
                'class_list' => $class_list,
                'exam_list'  => $exam_list,
                'score'       => $score
            ]);
        }
    }

    /**
     * 删除成绩
     * @param $id
     * @return void
     */
    public function delete($id = 0){
        if ($id !== 0 ) {
            $result = $this->score_model->destroy($id);
            if ($result) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败！err-1');
            }
        } else {
            $this->error("删除失败！err-2");
        }
    }
}